//index.js
import _music from '../../utils/music.js'

//const audio = wx.createInnerAudioContext()

const audio = wx.getBackgroundAudioManager()

let titflash = undefined

Page({
  data: {
    currentTab: 1,
    state: 0, // 播放状态
    order: 0, // 播放模式
    audioTime: 0, // 0-100 播放进度
    currentIndex: 0, // 歌词下标
    scrollTop: -1, // 歌词滚动顶部位置
    music: {
      title: '',
      author: '',
      url: '',
      pic: '/images/player_cover.png',
      lrc: '',
      lyrics: {}
    }, // 当前歌曲信息
    idx: -1, // 当前歌曲
    list: [], // 正在播放列表
    history: [], // 播放历史
    abum: [{
        id: 1,
        name: '正在播放',
        cover: '/images/player_cover.png'
      },
      {
        id: 2,
        name: '播放历史',
        cover: '/images/history.png'
      },
      {
        id: 3778678, 
        name: '云音乐热歌榜',
        cover: 'http://p1.music.126.net/GhhuF6Ep5Tq9IEvLsyCN7w==/18708190348409091.jpg?param=200y200'
      },
      {
        id: 3779629,
        name: '云音乐新歌榜',
        cover: 'http://p1.music.126.net/N2HO5xfYEqyQ8q6oxCw8IQ==/18713687906568048.jpg?param=200y200'
      },
      {
        id: 19723756,
        name: '云音乐飙升榜',
        cover: 'http://p1.music.126.net/DrRIg6CrgDfVLEph9SNh7w==/18696095720518497.jpg?param=200y200'
      },
      {
        id: 2884035,
        name: '网易原创歌曲榜',
        cover: 'http://p1.music.126.net/sBzD11nforcuh1jdLSgX7g==/18740076185638788.jpg?param=200y200'
      },
      {
        id: 4395559,
        name: '华语金曲榜',
        cover: 'http://p2.music.126.net/N2whh2Prf0l8QHmCpShrcQ==/19140298416347251.jpg?param=200y200'
      },
      {
        id: 71384707,
        name: '古典乐排行榜',
        cover: 'http://p2.music.126.net/BzSxoj6O1LQPlFceDn-LKw==/18681802069355169.jpg?param=200y200'
      },
      {
        id: 11641012,
        name: 'iTunes榜',
        cover: 'http://p2.music.126.net/WTpbsVfxeB6qDs_3_rnQtg==/109951163601178881.jpg?param=200y200'
      },
      {
        id: 64016,
        name: '中国TOP排行榜（内地榜）',
        cover: 'http://p1.music.126.net/2klOtThpDQ0CMhOy5AOzSg==/18878614648932971.jpg?param=200y200'
      },
      {
        id: 112504,
        name: '中国TOP排行榜（港台榜）',
        cover: 'http://p1.music.126.net/JPh-zekmt0sW2Z3TZMsGzA==/18967675090783713.jpg?param=200y200'
      },
      {
        id: 2809513713,
        name: '欧美热歌榜',
        cover: 'http://p1.music.126.net/c0iThrYPpnFVgFvU6JCVXQ==/109951164091703579.jpg?param=200y200'
      }
    ],
    server: [
      {
        value: 1,
        name: '网易云',
        server: 'netease',
        checked: 'true'
      },
      {
        value: 2,
        server: 'tencent',
        name: 'QQ音乐'
      },
      {
        value: 3,
        server: 'xiami',
        name: '虾米'
      },
      {
        value: 4,
        server: 'kugou',
        name: '酷狗'
      },
      {
        value: 5,
        server: 'baidu',
        name: '百度'
      },

    ]
  },
  // 切换 tab
  tabSelect: function(e) {
    this.setData({
      currentTab: e.target.dataset.id
    })
  },
  /* audio 部分 */
  // 初始化 audio
  init: function (idx) { 
    this.setData({
      idx: idx,
      music: this.data.list[idx]
    })
    audio.src = this.data.music.url
    audio.title = this.data.music.title
    audio.singer = this.data.music.author
    audio.coverImgUrl = this.data.music.pic
    audio.webUrl = this.data.music.url
    this.audioEvent()
    this.setHistory(this.data.music)
  },
  // audio 事件监听
  audioEvent: function() {
    let that = this
    audio.onError(()=>{
      wx.showToast({
        title: '播放失败',
        icon: 'none',
        duration: 3000
      })
      if(that.data.idx == -1) {
        that.setData({
          idx: 0
        })
      }
      that.next()
    })
    audio.onTimeUpdate(() => {
      that.setData({
        audioTime: (audio.currentTime / audio.duration) * 100
      })
    })
    audio.onPrev(() => {
      that.prev()
    })
    audio.onNext(()=>{
      that.next()
    })
    audio.onPlay(() => {
      clearInterval(titflash)
      titflash = setInterval(that.scroll, 1000)
      that.setData({
        state: 1
      })
    })
    audio.onPause(() => {
      that.pause()
    })
    audio.onStop(() => {
      that.stop()
    })
    audio.onEnded(() => {
      clearInterval(titflash)
      that.next()
      that.setData({
        audioTime: 0,
        scrollTop: -1
      })
    })
  },
  initAndPlay: function(e) {
    this.init(e.currentTarget.dataset.num)
    this.play()
  },
  /* 播放器部分 */ 
  // 播放/暂停
  switchState: function (e) {
    if (this.data.state == 0) {
      this.play()
    } else {
      this.pause()
    }
  },
  // 播放
  play: function () {
    if (this.data.idx == -1) {
      this.init(0)
    }
    audio.play()
    titflash = setInterval(this.scroll, 1000)
    this.setData({
      state: 1
    })
  },
  // 暂停
  pause: function () {
    audio.pause()
    clearInterval(titflash)
    this.setData({
      state: 0
    })
  },
  stop: function() {
    audio.stop()
    clearInterval(titflash)
    this.setData({
      state: 0,
      idx: -1,
      scrollTop: 0
    })
  },
  scroll: function () {
    this.scrollLyric(audio.currentTime)
  },
  // 歌词滚动
  scrollLyric: function (time) {
    let lyrics = this.data.music.lyrics;
    if (lyrics === undefined || lyrics === null|| lyrics === '') {
      clearInterval(titflash)
      return false
    }
    time = parseInt(time)
    if (lyrics[time] == undefined) {
      return true
    }
    let idx = 0; // 找到当前歌词在第几行
    for (let k in this.data.music.lyrics) {
      if (k == time) {
        break
      }
      idx++;
    }
    if (idx > 6) {
      this.setData({
        scrollTop: (idx - 5) * 30
      })
    }
    this.setData({
      currentIndex: time
    })
  },
  // 上一首
  prev: function () {
    clearInterval(titflash)
    let idx = (this.data.idx - 1) % this.data.list.length
    this.setData({
      idx: idx < 0 ? 0 : idx,
      scrollTop: 0
    })
    this.init(idx)
    this.play()
  },
  // 下一首
  next: function () {
    console.log('next...')
    clearInterval(titflash)
    let idx = (this.data.idx + 1) % this.data.list.length
    let order = this.data.order
    if (order == 1) {
      idx = parseInt(Math.random() * this.data.list.length)
    }
    this.setData({
      idx: idx,
      scrollTop: 0
    })
    this.init(idx)
    this.play()
  },
  // 循环模式
  order: function () {
    let _random = (this.data.order + 1) % 3;
    if (_random == 2) {
      audio.loop = true
    }
    this.setData({
      order: this.data.order == 2 ? 0 : _random
    })
  },
  // 拖拽进度条
  changeSlider: function (e) {
    let value = e.detail.value;
    this.setData({
      audioTime: value
    })
    let current = value / 100 * audio.duration
    audio.seek(current)
    // 歌词滚动
    this.scrollLyric(audio.currentTime)
    this.play()
  },
  // 播放列表部分
  switchList: function(e) {
    let id = e.currentTarget.dataset.id
    if(id == 2) {
      let history = this.getHistory()
      this.setData({
        list: history,
        currentTab: 1
      })
    } else if(id != 1){
        this.getMusicList(id)
        this.pause()
    }
    this.setData({
      currentTab: 1
    })
  },
  // 设置历史记录
  setHistory: function(music) {
    let history = this.data.history
    if(!history.includes(music)) {
      history.unshift(music)
      _music.setHistory(history)
      this.setData({
        history: history
      })
    }    
  },
  // 获取历史记录
  getHistory: function() {
    return _music.getHistory()
  },
  // 获取歌曲列表
  getMusicList: function(id) {
    _music.getMusicList(id).then((res) => {
      this.setData({
        idx: -1,
        list: res,
      })
    })
  },
  // 歌曲搜索部分
  search: function (e) {
    let keywords = e.detail.value.keywords
    let id = e.detail.value.server
    let server = this.data.server[id - 1].server
    let that = this
    _music.search(server, keywords).then((res)=> {
      that.setData({
        idx: -1,
        list: res,
        currentTab: 1
      })
      that.pause()
      that.play()
      that.hideModal()
    })
  },
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal() {
    this.setData({
      modalName: null
    })
  },
  onLoad: function () {
    // 背光常亮 
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
    // 设置可分享
    wx.showShareMenu()
    // 初始化播放列表
    this.getMusicList(3778678)
  },
  // 页面卸载时停止播放
  onUnload() {
    this.stop()
  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
  }
})
